package com.s59.Service;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.db.sql.Order;
import com.s59.dao.BookDao;
import com.s59.dao.BootOrderDao;
import com.s59.entity.BootOrder;
import com.s59.mp.SczMp;
import com.s59.mp.XfzMp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class BootOrderService {
    @Autowired
    private SczMp sczMp;
    @Autowired
    private BootOrderDao bootOrderDao;
    @Autowired
    private BookDao bookDao;
    @Autowired
    private Snowflake snowflake;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public void createOrder(BootOrder bootOrder){
        bootOrder.setCreateTime(new Date());
        if(bootOrder.getOrderId() == null){
            bootOrder.setOrderId(snowflake.nextIdStr());
        }
        bootOrder.setStatus(0);
        if(bootOrder.getMoney() == null){
            bootOrder.setMoney(bookDao.findById(bootOrder.getBookId()).get().getPrice());
        }
        bootOrderDao.save(bootOrder);
    }

    public void seafcreateOrder(BootOrder bootOrder) {
        bootOrder.setOrderId(snowflake.nextIdStr());
        sczMp.sead3(bootOrder,null);
    }

    public boolean ms(Long bookId, Integer userId) {
        DefaultRedisScript<String> redisScript = new DefaultRedisScript();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("stock_simple.lua")));
        redisScript.setResultType(String.class);
        List<String> keys = new ArrayList<>();
        keys.add(BookService.SK_BOOK_KEY);
        StringRedisSerializer serializer = new StringRedisSerializer();
        String res = redisTemplate.execute(redisScript,serializer,serializer,keys,bookId.toString());
        if(!"1".equals(res)){
            return false;
        }
        BootOrder order = new BootOrder();
        order.setUserId(userId);
        order.setBookId(bookId);
        seafcreateOrder(order);
        return true;
    }
}
